package com.webflux.sample.webfluxapp.gen;

public class SnowflakeIdGenerator {

    // Timestamp of the last Snowflake ID generation
    private static long lastTimestamp = -1L;

    // Number of bits for each component of the Snowflake ID
    private static final long SEQUENCE_BIT = 12;
    private static final long WORKER_ID_BIT = 5;
    private static final long DATA_CENTER_ID_BIT = 5;

    // Maximum values for each component of the Snowflake ID
    private static final long MAX_SEQUENCE_NUM = ~(-1L << SEQUENCE_BIT);
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BIT);
    private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BIT);

    // Shift values for each component of the Snowflake ID
    private static final long WORKER_ID_SHIFT = SEQUENCE_BIT;
    private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BIT + WORKER_ID_BIT;
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BIT + WORKER_ID_BIT + DATA_CENTER_ID_BIT;

    // Components of the Snowflake ID
    private final long workerId;
    private final long dataCenterId;
    private long sequence = 0L;
    private long lastGeneratedTimestamp = -1L;

    public SnowflakeIdGenerator(long workerId, long dataCenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker ID must be between 0 and %d", MAX_WORKER_ID));
        }
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("Data center ID must be between 0 and %d", MAX_DATA_CENTER_ID));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    public synchronized long generateId() {
        long currentTimestamp = System.currentTimeMillis();

        if (currentTimestamp < lastGeneratedTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID.");
        }

        if (currentTimestamp == lastGeneratedTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE_NUM;
            if (sequence == 0) {
                currentTimestamp = nextTimestamp(lastGeneratedTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastGeneratedTimestamp = currentTimestamp;

        return (currentTimestamp << TIMESTAMP_LEFT_SHIFT) |
                (dataCenterId << DATA_CENTER_ID_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    private long nextTimestamp(long lastTimestamp) {
        long currentTimestamp = System.currentTimeMillis();
        while (currentTimestamp <= lastTimestamp) {
            currentTimestamp = System.currentTimeMillis();
        }
        return currentTimestamp;
    }
}